<script setup lang="ts">
import { createVNode, reactive, ref } from "vue";
import { serchOptions, columns } from "./data.ts";
import {
  IUserTableParams,
  IResetPwdState,
  ITableData,
  ITypeState,
} from "./types.ts";
import { fetchTabelData, delRow, addRow } from "@/api/common";
import { PAGE_NUMBER, PAGE_SIZE } from "@/utils/const.ts";
import { IOperHandle, ITableResPage } from "@/utils/types/table.ts";
import AddModal from "./AddModal.vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { message, Modal, TreeProps } from "ant-design-vue";
import JModal from "@/components/global/Modal/JModal.vue";
import { treeselect } from "@/api/system/user.ts";
let tableParams = reactive<IUserTableParams>({
  pageNum: PAGE_NUMBER,
  pageSize: PAGE_SIZE,
});
const state = reactive<ITypeState>({
  tableData: [],
  loading: false,
  total: 0,
});
const addModalRef = ref();
const resetPwdRef = ref();
const resetPwd = reactive<IResetPwdState>({
  userId: 0,
  password: "",
});
const getList = async (params: IUserTableParams) => {
  state.loading = true;
  tableParams = Object.assign({}, params);
  const { rows, total }: ITableResPage<ITableData> = await fetchTabelData<
    IUserTableParams,
    ITableData
  >(tableParams, "/system/user/list");
  state.tableData =
    rows?.map((item: ITableData) => ({
      ...item,
      statusName: item.status === "0" ? "正常" : "停用",
      deptName: item.dept.deptName,
    })) || [];
  state.total = total || 0;
  state.loading = false;
};
getList(tableParams);
const initTableData = (parmas: IUserTableParams) => {
  if (JSON.stringify(parmas) === "{}") {
    // 重置
    tableParams = reactive({
      pageNum: PAGE_NUMBER,
      pageSize: PAGE_SIZE,
    });
  } else {
    const pp = {
      ...parmas,
      pageNum: parmas.pageNum ? parmas.pageNum : PAGE_NUMBER,
      pageSize: parmas.pageSize ? parmas.pageSize : PAGE_SIZE,
    };
    tableParams = Object.assign(tableParams, pp);
  }
  getList(tableParams);
};
const operHandleFun: IOperHandle<ITableData | null> = {
  handleResetPwd: (row: ITableData | null) => {
    resetPwd.userId = row?.userId || 0;
    resetPwd.password = "";
    resetPwdRef.value.openModal();
  },
  // 添加
  handleAdd: (row: ITableData | null, type: string) => {
    addModalRef.value.openAddModal(type, row);
  },
  handleDelete: (row: ITableData | null, url: string) => {
    Modal.confirm({
      title: "删除",
      icon: createVNode(ExclamationCircleOutlined),
      content: "是否确认删除该数据？",
      async onOk() {
        await delRow(`${url}/${row?.userId}`, "delete");
        initTableData(tableParams);
      },
    });
  },
};
const operHandle = (fun: string, row: ITableData | null, type: string) => {
  operHandleFun[fun](row, type);
};
const resetPwdOk = async () => {
  if (resetPwd.password) {
    const { msg } = await addRow<IResetPwdState>(
      "/system/user/resetPwd",
      resetPwd,
      "put",
    );
    message.success(msg);
    initTableData(tableParams);
    resetPwdRef.value.closeModal();
  } else {
    message.error("请输入密码");
  }
};
// 树形数据
const searchValue = ref<string>("");
const autoExpandParent = ref<boolean>(true);
const deptTreeData = ref<TreeProps["treeData"]>([]);
const getDeptTree = async () => {
  const { data } = await treeselect();
  deptTreeData.value = data;
};
getDeptTree();
const treeSelectHandle = (selectedKeys: number[]) => {
  tableParams.deptId = selectedKeys[0];
  tableParams.pageNum = PAGE_NUMBER;
  getList(tableParams);
};
</script>

<template>
  <div class="page-index flex">
    <div class="flex-left-dept">
      <a-card :title="null" :bordered="false" style="height: 100%">
        <a-input-search
          v-model:value="searchValue"
          style="margin-bottom: 8px"
          placeholder="搜索"
        />
        <a-tree
          v-if="deptTreeData && deptTreeData.length"
          :auto-expand-parent="autoExpandParent"
          defaultExpandAll
          :tree-data="deptTreeData"
          :fieldNames="{ children: 'children', title: 'label', key: 'id' }"
          @select="treeSelectHandle"
        >
          <template #title="{ label }">
            <span v-if="label.indexOf(searchValue) > -1">
              {{ label.substring(0, label.indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{
                label.substring(label.indexOf(searchValue) + searchValue.length)
              }}
            </span>
            <span v-else>{{ label }}</span>
          </template>
        </a-tree>
      </a-card>
    </div>
    <div class="flex-one-all">
      <JTableSearch
        :searchList="serchOptions"
        @setTableParams="initTableData"
      />
      <JTableIndex
        title="用户列表"
        :columns="columns"
        rowKey="deptId"
        :loading="state.loading"
        :listData="state.tableData"
        :setPages="tableParams"
        @operHandle="operHandle"
        @tableChange="initTableData"
      >
        <template v-slot:table-right>
          <a-button
            type="primary"
            v-hasPermi="['system:user:add']"
            @click="operHandle('handleAdd', null, 'add')"
          >
            + 新增
          </a-button>
        </template>
      </JTableIndex>
      <add-modal ref="addModalRef" @refresh="initTableData" />
    </div>
  </div>
  <JModal
    title="重置密码"
    :width="400"
    ref="resetPwdRef"
    @handleOk="resetPwdOk"
  >
    <template #default>
      <a-form-item label="新密码">
        <a-input v-model:value="resetPwd.password" />
      </a-form-item>
    </template>
  </JModal>
</template>
<style lang="less" scoped>
.flex-left-dept {
  flex: 0 0 240px;
  margin-right: 20px;
  height: calc(100vh - 190px);
}
</style>
